<?php
class Product_Service_PutawayProccess
{
    protected $_quantity = null;
    protected $_wscode = null;
    protected $_putawayLotNumber = null;
    protected $_productId = null;
    protected $_productSku = null;
    protected $_qcPutawayIds = null; //有可能来自QC上架草稿
    protected $_putawayId = null; //上架ID confirm确认上架时才用到
    protected $_putawayCode = null; // 确认上架
    //以上都是Array类型
    protected $_receivingCode = null; //string
    protected $_warehouseId = 1;
    protected $_confirm = 0; //提示信息等待确认

    protected $_status = null; //0:上架 1:确认上架
    protected $_putaway = null;
    protected $_error = null;
    protected $_userId = null;
    protected $_putawayData = array();
    protected $_CustomerId = null;
    protected $_message = null;
    /*
     * 上架及上架确认初始化数据
    $array=array(
        'quantity'=>,
        'wscode'=>
        'putawayLotNumber'=>
        'productId'=>
        'productSku'=>
        'receivingCode'=>
        'confirm'=>0超过占用率须确认
        'qcPutawayIds'=>,草稿上架数量ID,上架时才可能用到
        'putawayCode'=>,上架确认才需要,
        'putawayId'=>,上架确认才需要,
    );
    */
    public function __construct($array = null)
    {
        if ($array != null) {
            foreach ($array as $key => $val) {
                $this->set('_' . $key, $val);
            }
        }
    }

    public function set($key, $value)
    {
        $this->$key = $value;
    }

    private function validation(){

    }

    private function setUser()
    {
        if (empty($this->_userId) || $this->_userId == null) {
            $session = new Zend_Session_Namespace('userAuth');
            $this->_userId = isset($session->userID) ? $session->userID : 0;
        }
    }

    private function setCustomerId()
    {
        $receivingRow = Product_Service_Receiving::getByReceivingCode($this->_receivingCode);
        if (empty($receivingRow)) {
            $this->_error[] = 'ASN:' . $this->_receivingCode . '不存在.';
            return false;
        }
        $this->_CustomerId = $receivingRow['customer_id'];
    }

    /*
     * 判断是否通过QC
     */
    private  function  checkQC(){
        $qcModel=new Product_Model_QualityControlOrder();
        foreach ($this->_productId as $key => $val) {
            $qcWhere=array(
                'qco_ref_code'=>$this->_receivingCode,
                'product_id'=>$val
            );
            $qcRow=$qcModel->getJoinQcItem($qcWhere);
            if(empty($qcRow)){
                $this->_error[] = '操作失败,ASN:'.$this->_receivingCode.' 获取QC数据失败.'.$val;
                return false;
            }elseif(!isset($qcRow['qci_status']) || $qcRow['qci_status']!='3' ){
                $this->_error[] = '操作失败,ASN:'.$this->_receivingCode .' QC:'.$qcRow['qco_code'] .'未完成质检.'.$val;
                return false;
            }
        }
        return true;
    }

    /*
    * 上架、确认上架 数据验证
    */
    private function validate()
    {

        $error = array();
        if ($this->_status == '') {
            $error[] = "操作失败,未设置上架状态." . $this->_status;
        }
        //验证上架数量
        foreach ($this->_quantity as $key => $val) {
            if ($val < 1 || $val == '' || !preg_match("/^\d+$/", $val)) {
                $error[] = "批次: " . $this->_putawayLotNumber[$key] . " ,上架数量不能小于或等于0";
            } //不允许数量为0
        }
        //验证货架号
        $putawayShelf = array();
        foreach ($this->_wscode as $key => $val) {
            $errorWscode = false;
            if ($val == '') {
                $error[] = "批次:" . ($this->_putawayLotNumber[$key]) . " ,货架号不能为空!";
            } else {
                $condition = array(
                    'ws_code' => $val,
                    'product_id' => $this->_productId[$key],
                );
                $wssRow = Warehouse_Service_Shelf::getByfield('ws_code', $val);
                $wspRow = Warehouse_Service_Products::getByCondition(array('ws_code' => $val, 'warehouse_id' => 1));
                //$wspRow = Warehouse_Service_Products::getByCondition(array('ws_code' => $val, 'wp_status' => '1'));
                if (!empty($wspRow)) {
                    if ($wspRow['product_id'] != $this->_productId[$key] && $wspRow['wp_status']=='1' ) {
                        $errorWscode = true;
                    }
                }
                if (empty($wssRow)) {
                    $error[] = "货架号:" . $val . "不存在!";
                } elseif ($wssRow['ws_statu'] != 1) {
                    $error[] = "货架号:" . $val . "不可用!";
                } elseif(isset($wspRow['wp_status']) && $wspRow['wp_status']=='2'){
                    $error[] = "货架号:" . $val . "进行盘点中,不允许上架!";
                } elseif ($errorWscode) {
                    $error[] = "货架号:" . $val . "已经存放其它的产品! " . $wspRow['product_id'] . '  >>  ' . $this->_productId[$key];
                } elseif (!Warehouse_Service_Shelf::getByJoinChooseCondition($condition, "count(*)")) {
                    $error[] = "货架号:" . $val . "与产品目录不符!";
                } else {
                    $option = array(
                        'putaway_status_in' => array('0','-1'),//草稿、未确认
                        'ws_code' => $val,
                    );
                    $pRows = Product_Service_Putaway::getByCondition($option, "*", '', 0, 0);
                    if (!empty($pRows)) {
                        if ($pRows[0]['product_id'] != $this->_productId[$key]) {
                            $error[] = "货架号:" . $val . " 已被 " . $pRows[0]['putaway_code'] . " 批次 " . $pRows[0]['putaway_lot_number'] . " 占用!";
                        }
                    }
                }
            }
            $putawayShelf[$this->_productId[$key]][] = $val;
        }

        //验证多个产品使用同一个货架号
        $typeWscode = array();
        foreach ($putawayShelf as $key => $value) {
            $typeWscode[$key] = array();
            foreach ($putawayShelf[$key] as $k => $v) {
                if (!in_array($v, $typeWscode[$key])) {
                    $typeWscode[$key][] = $v;
                }
            }
        }
        //合并各产品货架号
        $mergeWscode = array();
        foreach ($typeWscode as $key => $value) {
            foreach ($value as $k => $v) {
                $mergeWscode[] = $v;
            }
        }
        //查找重复的货架号
        $arrayCount = array_count_values($mergeWscode);
        foreach ($arrayCount as $key => $value) {
            if ($value > 1) {
                $error[] = "货架号:" . $key . " 不可以多个产品共用一个货架号!";
            }
        }
        //查找重复的批次
        $arrayCount = array_count_values($this->_putawayLotNumber);
        foreach ($arrayCount as $key => $value) {
            if ($value > 1) {
                $error[] = "批次:" . $key . " 不允许重复批次号!";
            }
        }

        if (!empty($error)) {
            $this->_error = $error;
            return false;
        }

        if ($this->_status == 0) { //用于验证创建上架时
            if ($this->_receivingCode == '' || $this->_receivingCode == null) {
                $this->_error = array("ASN,不能为空!");
                return false;
            }
            //验证产品个数/提交数量
            $product_total = array(); //提交总数
            $productIds = array(); //产品ID
            $productSKU = array(); //产品SKU
            foreach ($this->_productId as $key => $val) {
                if (!in_array($val, $productIds)) {
                    $productIds[] = $val;
                    $product_total[$val] = 0;
                    $productSKU[$val] = $this->_productSku[$key];
                }
                if (in_array($val, $productIds)) {
                    $product_total[$val] += $this->_quantity[$key];
                }
            }
            //数量不能大于等待上架数量
            foreach ($productIds as $key => $val) {
                $cond = array(
                    'product_id' => $val,
                    'receiving_code' => $this->_receivingCode,
                );
                $PSRrows = Product_Service_ReceivingItem::getByReceivingAsnPid($cond);
                $waitTotal = $PSRrows['received_qty'] - $PSRrows['putaway_qty']; //等上架总数量

                //QC通过数量验证
                if ($PSRrows['is_qc'] == '1') {
                    $waitTotal = 0;
                    $qcCount = 0; //通过QC数量
                    $qcCount = Product_Service_QualityControlOrder::getByQcoRefCodeAndProductId($cond['receiving_code'], $cond['product_id']);
                    if ($qcCount > 0) {
                        $waitTotal = $qcCount - $PSRrows['putaway_qty'];
                    }
                }

                if ($product_total[$val] > $waitTotal) {
                    $error[] = "产品SKU:" . $productSKU[$val] . ",上架数量(" . $product_total[$val] . ")大于待上架总数量(" . $waitTotal . ")!";
                }
            }
        } else { //用于验证确认上架
            if (empty($this->_putawayId)) {
                $this->_error[] = "提交数据有误putaway_id,不能为空.";
                return false;
            }
            if (empty($this->_putawayCode) || empty($this->_receivingCode)) {
                $this->_error[] = "提交数据有误ASN或上架单号为空.";
                return false;
            }
            //验证产品个数/提交数量/重复提交
            $putaway_total = array(); //提交总数
            $putawayIds = array(); //上架ID
            $putawayproductSKU = array(); //产品SKU
            foreach ($this->_putawayId as $key => $val) {
                $psprows = Product_Service_Putaway::getByPutawayId($val);
                if ($psprows['putaway_status'] == '-1') {
                    $error[] = "LotID: " . $psprows['putaway_lot_number'] . " 草稿状态,不允许上架!";
                }elseif($psprows['putaway_status'] == '1'){
                    $error[] = "LotID: " . $psprows['putaway_lot_number'] . " 已完成上架,请勿重复提交!";
                }
                if (!in_array($val, $putawayIds)) {
                    $putawayIds[] = $val;
                    $putaway_total[$val] = 0;
                    $putawayproductSKU[$val] = $this->_productSku[$key];
                }
                if (in_array($val, $putawayIds)) {
                    $putaway_total[$val] += $this->_quantity[$key];
                }
            }
            //修改后的数量不能大于当前上架数量
            foreach ($putawayIds as $key => $val) {
                $psprows = Product_Service_Putaway::getByPutawayId($val);
                if ($putaway_total[$val] > $psprows['putaway_quantity']) {
                    $error[] = "产品SKU:" . $putawayproductSKU[$val] . ",修改后的上架数量(" . $putaway_total[$val] . "),不能大于上架总数量(" . $psprows['putaway_quantity'] . ")!";
                }
            }
        }

        if (!empty($error)) {
            $this->_error = $error;
            return false;
        }
        return true;
    }

    private function rate()
    {
        //验证产品个数/提交数量
        $putawayTotal = array(); //提交总数
        $shelfproductId = array(); //产品ID
        $wscode = array(); //货架号
        foreach ($this->_wscode as $key => $val) {
            if (!in_array($val, $wscode)) {
                $wscode[] = $val;
                $putawayTotal[$val] = 0;
            }
            if (in_array($val, $wscode)) {
                $putawayTotal[$val] += $this->_quantity[$key];
                $shelfproductId[$val] = $this->_productId[$key];
            }
        }
        //计算占用率
        $rateMsg = array();
        foreach ($putawayTotal as $key => $val) {
            $rateRow = new Warehouse_Service_OccupancyRate(array('product_id' => $shelfproductId[$key], 'quantity' => $val, 'ws_code' => $key));
            $result = $rateRow->getRate();
            if (isset($result['ask']) && $result['ask'] == 1) {
                if ($result['rate']['total'] > 120) {
                    $rateMsg[] = '上架后,货架:' . $key . '占用率将超过20%';
                }
            }
        }
        if (!empty($rateMsg)) {
            $this->_message = $rateMsg;
        }
    }

    /*
     * 创建上架
     * return array('ask'=>0,'msg'=>,'putawayCode=>'')
     */
    public function createPutaway()
    {
        $this->_status = '0'; //创建上架
        $this->validate();
        $this->setUser();
        $this->setCustomerId();
        if (!empty($this->_error)) {
            return array('ask' => 0, 'msg' => $this->_error);
        }
        //已不使用此方法
        return array('ask' => 0, 'msg' => '此程序已不使用.');
        /* 占用率的提示暂时不用
        $this->rate();
        if (!empty($this->_message) && $this->_confirm == '0') {
            return array('ask' => 2, 'msg' => $this->_message);
        }
        */
        if (!empty($this->_qcPutawayIds)) {
            $qcPutawayIds = array();
            foreach ($this->_qcPutawayIds as $key => $val) {
                if (!in_array($val, $qcPutawayIds)) {
                    $qcPutawayIds[] = $val;
                }
            }
        }

        $WMProducts = new Warehouse_Model_Products();
        $dbAdapter = $WMProducts->getAdapter();
        $dbAdapter->beginTransaction();
        try {
            //删除提交时的草稿putaway_code
            if (isset($qcPutawayIds) && is_array($qcPutawayIds)) {
                $putawayModel = new Product_Model_Putaway();
                foreach ($qcPutawayIds as $val) {
                    if (!$putawayModel->delete($val)) {
                        $dbAdapter->rollback();
                        $this->_error[] = '处理QC上架失败.';
                        return array('ask' => 0, 'msg' => $this->_error);
                    }
                }
            }
            $newPutawayCode = Product_Service_Putaway::getCurdateLastCode(); //查找当天最后一个
            $date=date("Y-m-d H:i:s");
            foreach ($this->_productId as $key => $val) {
                $putawayRow = array(
                    'receiving_code' => $this->_receivingCode,
                    'putaway_code' => $newPutawayCode,
                    'product_id' => $val,
                    'putaway_create_date' => $date,
                    'warehouse_id' => $this->_warehouseId,
                    'create_user_id' => $this->_userId,
                    'putaway_note' => 'create',
                    'putaway_status' => 0, //等待确认
                    'putaway_quantity' => $this->_quantity[$key], //上架数量
                    'putaway_lot_number' => $this->_putawayLotNumber[$key], //上架批次号
                    'ws_code' => strtoupper($this->_wscode[$key]), //货架号
                );
                if (Product_Service_Putaway::create($putawayRow)) {
                    //上架日志
                    $this->createPutawayLog(0,0,$newPutawayCode,'产品ID:'.$val.' 货架号:'.$this->_wscode[$key].' 数量:'.$this->_quantity[$key]);
                } else {
                    $dbAdapter->rollback();
                    $this->_error[] = '创建上架单失败.';
                    return array('ask' => 0, 'msg' => $this->_error);
                }
            }
            $dbAdapter->commit();
            return array('ask' => 1, 'msg' => '操作成功.', 'putawayCode' => $newPutawayCode);
        } catch (Exception $e) {
            $dbAdapter->rollback();
            $this->_error[] = $e->getMessage();
            return array('ask' => 0, 'msg' => $this->_error);
        }
    }

    /*
    * 确认上架 数据验证
    */
    private function confirmValidate()
    {
        $error = array();
        //验证上架数量
        foreach ($this->_quantity as $key => $val) {
            if ($val < 1 || $val == '' || !preg_match("/^\d+$/", $val)) {
                $error[] = '上架单号:' . $this->_putawayCode[$key] . " 批次: " . $this->_putawayLotNumber[$key] . " ,上架数量不能小于或等于0";
            } //不允许数量为0
        }
        //验证货架号
        $putawayShelf = array();
        foreach ($this->_wscode as $key => $val) {
            $errorWscode = false;
            if ($val == '') {
                $error[] = '上架单号:' . $this->_putawayCode[$key] ." 批次:" . ($this->_putawayLotNumber[$key]) . " ,货架号不能为空!";
            } else {
                $condition = array(
                    'ws_code' => $val,
                    'product_id' => $this->_productId[$key],
                );
                $wssRow = Warehouse_Service_Shelf::getByfield('ws_code', $val);
                $wspRow = Warehouse_Service_Products::getByCondition(array('ws_code' => $val, 'warehouse_id' => 1));
                if (!empty($wspRow)) {
                    if ($wspRow['product_id'] != $this->_productId[$key] && $wspRow['wp_status'] == '1') {
                        $errorWscode = true;
                    }
                }
                if (empty($wssRow)) {
                    $error[] = "货架号:" . $val . "不存在!";
                } elseif ($wssRow['ws_statu'] != 1) {
                    $error[] = "货架号:" . $val . "不可用!";
                } elseif (isset($wspRow['wp_status']) && $wspRow['wp_status'] == '2') {
                    $error[] = "货架号:" . $val . "进行盘点中,不允许上架!";
                } elseif ($errorWscode) {
                    $error[] = "货架号:" . $val . "已经存放其它的产品! " . $wspRow['product_id'] . '  >>  ' . $this->_productId[$key];
                } elseif (!Warehouse_Service_Shelf::getByJoinChooseCondition($condition, "count(*)")) {
                    $error[] = "货架号:" . $val . "与产品目录不符!";
                } else {
                    $option = array(
                        'putaway_status_in' => array('0', '-1'), //草稿、未确认
                        'ws_code' => $val,
                    );
                    $pRows = Product_Service_Putaway::getByCondition($option, "*", '', 0, 0);
                    if (!empty($pRows)) {
                        if ($pRows[0]['product_id'] != $this->_productId[$key]) {
                            $error[] = "货架号:" . $val . " 已被 " . $pRows[0]['putaway_code'] . " 批次 " . $pRows[0]['putaway_lot_number'] . " 占用!";
                        }
                    }
                }
            }
            $putawayShelf[$this->_productId[$key]][] = $val;
        }

        //验证多个产品使用同一个货架号
        $typeWscode = array();
        foreach ($putawayShelf as $key => $value) {
            $typeWscode[$key] = array();
            foreach ($putawayShelf[$key] as $k => $v) {
                if (!in_array($v, $typeWscode[$key])) {
                    $typeWscode[$key][] = $v;
                }
            }
        }
        //合并各产品货架号
        $mergeWscode = array();
        foreach ($typeWscode as $key => $value) {
            foreach ($value as $k => $v) {
                $mergeWscode[] = $v;
            }
        }
        //查找重复的货架号
        $arrayCount = array_count_values($mergeWscode);
        foreach ($arrayCount as $key => $value) {
            if ($value > 1) {
                $error[] = "货架号:" . $key . " 不可以多个产品共用一个货架号!";
            }
        }

        if (empty($this->_putawayId) || !is_array($this->_putawayId) ) {
            $this->_error[] = "提交数据有误putaway_id,不能为空.";
            return false;
        }
        if (empty($this->_putawayCode) || empty($this->_receivingCode)) {
            $this->_error[] = "提交数据有误ASN或上架单号为空.";
            return false;
        }
        //验证产品个数/提交数量/重复提交
        $putawayTotal = array(); //提交总数
        $putawayIds = array(); //上架ID
        foreach ($this->_putawayId as $key => $val) {
            if($val==0 || $val=='' ){
                continue;
            }
            $psprows = Product_Service_Putaway::getByPutawayId($val);
            if (!isset($psprows['putaway_status']) ||  $psprows['putaway_status'] == '-1') {
                $error[] = "上架单:".$psprows['putaway_code']." 编号:" . $psprows['putaway_lot_number'] . " 草稿状态,不允许上架!";
            } elseif ($psprows['putaway_status'] == '1') {
                $error[] = "上架单:".$psprows['putaway_code']." 编号:" . $psprows['putaway_lot_number'] . " 已完成上架,请勿重复提交!";
            }
            if(!empty($psprows)){
                $putawayTotal[$psprows['product_id']]=$psprows['putaway_quantity'];
            }

        }

        if (!empty($error)) {
            $this->_error = $error;
            return false;
        }

        $productTotal = array(); //提交总数
        $productIds = array(); //产品ID
        $productSku = array(); //产品SKU
        foreach ($this->_productId as $key => $val) {
            //统计各产品提交数量
            if (!in_array($val, $productIds)) {
                $productIds[] = $val;
                $productTotal[$val] = 0;
                $productSku[$val] = $this->_productSku[$key];
            }
            if (in_array($val, $productIds)) {
                $productTotal[$val] += $this->_quantity[$key];
            }
        }
        //修改后的数量不能大于当前上架数量
        foreach ($productTotal as $key => $val) {
            if($val==0){
                $error[] = "产品SKU:" . $productSku[$key] . "数据异常.";
                continue;
            }
            if ($val > $putawayTotal[$key] ) {
                $error[] = "产品SKU:" . $productSku[$key] . ",修改后的上架数量(" . $val . "),不能大于上架总数量(" . $putawayTotal[$key] . ")!";
            }
        }

        if (!empty($error)) {
            $this->_error = $error;
            return false;
        }
        return true;
    }

    /*
     * 确认上架/添加库存
     * return array('ask'=>0,'msg'=>,'putawayCode=>'')
     */
    public function confirmPutaway()
    {
        $this->_status = 1; //确认上架
        $this->confirmValidate();
        $this->setUser();
        $this->setCustomerId();
        $this->checkQC();
        if (!empty($this->_error)) {
            return array('ask' => 0, 'msg' => $this->_error);
        }
        $date = date("Y-m-d H:i:s");
        $WMProducts = new Warehouse_Model_Products();
        $dbAdapter = $WMProducts->getAdapter();
        $dbAdapter->beginTransaction();
        try {
            //验证产品个数/提交数量
            $product_total = array(); //提交总数
            $productIds = array(); //产品ID
            foreach ($this->_productId as $key => $val) {
                if (!empty($this->_putawayData)) {
                    $this->_putawayData = null;
                }
                $putawayRow = array(
                    'putaway_id' => $this->_putawayId[$key],
                    'receiving_code' => $this->_receivingCode,
                    'putaway_code' => $this->_putawayCode[$key],
                    'putaway_date' => $date,
                    'putaway_create_date' => $date,
                    'warehouse_id' => $this->_warehouseId,
                    'create_user_id' => $this->_userId,
                    'putaway_user_id' => $this->_userId,
                    'putaway_note' => 'create',
                    'product_id' => $val,
                    'putaway_status' => '1', //1.已完成
                    'putaway_quantity' => $this->_quantity[$key], //上架数量
                    'putaway_lot_number' => $this->_putawayLotNumber[$key], //上架批次号
                    'ws_code' => strtoupper($this->_wscode[$key]), //货架号
                );

                $this->_putawayData = $putawayRow;

                if (!$this->procPutaway()) {
                    $dbAdapter->rollback();
                    $this->_error[] = '更新上架单失败.' . $this->_putawayLotNumber[$key];
                    return array('ask' => 0, 'msg' => $this->_error);
                }

                //统计各产品提交数量
                if (!in_array($val, $productIds)) {
                    $productIds[] = $val;
                    $product_total[$val] = 0;
                }
                if (in_array($val, $productIds)) {
                    $product_total[$val] += $this->_quantity[$key];
                }
            }
            //更新产品库存/写入日志
            foreach ($product_total as $key => $val) {
                if (!Product_Service_ProductStocket::updateQuantity($key, $val)) {
                    $dbAdapter->rollback();
                    $this->_error[] = '更新产品库存失败.';
                    return array('ask' => 0, 'msg' => $this->_error);
                }
            }
            $dbAdapter->commit();
            return array('ask' => '1', 'msg' => '操作成功.','receivingCode'=>$this->_receivingCode);
        } catch (Exception $e) {
            $dbAdapter->rollback();
            $this->_error[] = $e->getMessage();
            return array('ask' => '0', 'msg' => $this->_error);
        }

    }

    private function procPutaway()
    {
        if (empty($this->_putawayData)) {
            throw new Exception('上架数据不能为空.');
            return false;
        }
        //判断如果putawayid已存在，则修改，反之添加
        $putawayRow = Product_Service_Putaway::getByPutawayId($this->_putawayData['putaway_id']);
        if (!empty($putawayRow)) {
            $updateRow = array(
                'putaway_date' => $this->_putawayData['putaway_date'],
               // 'putaway_note' => 'confirm',
                'putaway_user_id' => $this->_putawayData['putaway_user_id'],
                'putaway_status' => 1, //confirm 状态已完成
                'ws_code' => $this->_putawayData['ws_code'],
                'putaway_quantity' => $this->_putawayData['putaway_quantity'], //上架数量
            );
            if (!Product_Service_Putaway::update($updateRow, $this->_putawayData['putaway_id'])) {
                throw new Exception('更新上架状态失败!上架单:'.$this->_putawayData['putaway_code'].' 批次:' . $this->_putawayData['putaway_lot_number']);
                return false;
            }
        } else {
            unset($this->_putawayData['putaway_id']);
            if (!Product_Service_Putaway::create($this->_putawayData)) {
                throw new Exception('创建上架批次失败!'.$this->_putawayData['putaway_code'].' 批次:' . $this->_putawayData['putaway_lot_number']);
                return false;
            }
        }
        //获取QC CODE
        $this->_putawayData['qco_code'] = '';
        $qcModel=new Product_Model_QualityControlOrder();
        $qcWhere=array(
            'qco_ref_code'=>$this->_receivingCode,
            'product_id'=>$this->_putawayData['product_id']
        );
        $qcRow=$qcModel->getJoinQcItem($qcWhere);
        if (!empty($qcRow)) {
                $this->_putawayData['qco_code'] = $qcRow['qco_code'];
        }

        $this->createWarehouseProducts();
        $this->createProductsBatch();
        //上架日志
        $this->createPutawayLog((isset($where['putaway_code'])?'1':'0'),1,$this->_putawayData['putaway_code'],'产品ID:'.$this->_putawayData['product_id'].' 货架号:'. $this->_putawayData['ws_code'] .' 数量:'.$this->_putawayData['putaway_quantity']);
        //更新上架数量
        $this->updateAsnOrQcPutawayQty($this->_putawayData['product_id'],$this->_putawayData['putaway_quantity']);
        return true;

    }

    /*
     * 添加货架库存/日志 /更新pallet
     */
    private function createWarehouseProducts()
    {
        $date = date('Y-m-d H:i:s');
        $condition = array(
            'ws_code' => $this->_putawayData['ws_code'],
            'warehouse_id' => $this->_putawayData['warehouse_id'],
        );
        $wspRows = Warehouse_Service_Products::getByCondition($condition);
        $wplProcType = 1;
        $wplNote = '';
        if (!empty($wspRows)) {
            $wmpRowobj = new Warehouse_Model_Products();
            $wspRow = $wmpRowobj->lockForUpdate($condition); //lockFor

            //状态不可用才更新为可用，避免还有其它状态
            if ($wspRows['wp_status'] == '0') {
                $quantityupdateRow['wp_status'] = 1;
                $quantityupdateRow['wp_quantity'] = $this->_putawayData['putaway_quantity'];
                $quantityupdateRow['wp_quantity_hold'] = 0;
                $quantityupdateRow['product_id'] = $this->_putawayData['product_id'];

                $wplProcType = 3; //内容修改
                $wplNote = 'putaway,status:0 to 1;quantity:0 to ' . $this->_putawayData['putaway_quantity'];

                if ($wspRows['product_id'] != $this->_putawayData['product_id']) {
                    $wplNote .= 'productID: ' . $wspRows['product_id'] . ' to  ' . $this->_putawayData['product_id'];
                }

            } elseif ($wspRows['wp_status'] == '1' && $wspRows['product_id'] == $this->_putawayData['product_id']) {

                $quantityupdateRow['wp_quantity'] = $wspRow['wp_quantity'] + $this->_putawayData['putaway_quantity'];
                $wplProcType = 1; //增加库存
                $wplNote = 'putaway,quantity:' . $wspRow['wp_quantity'] . ' to ' . $quantityupdateRow['wp_quantity'];

            } else {
                //其它的状态情况不允许上架
                throw new Exception('货架号:' . $this->_putawayData['ws_code'] . '状态(' . $wspRows['wp_status'] . ')异常,上架失败!' . $wspRows['product_id'] . '=>' . $this->_putawayData['product_id']);
                return false;
            }

            //修改库存
            $quantityupdateRow['wh_last_update'] = $date;
            if ($wmpRowobj->update($quantityupdateRow, $wspRow['wp_id'])) {
                //写入货架使用日志
                $this->CreateWarehouseProductsLog($wplNote, $wplProcType);
            } else {
                throw new Exception('更新货架库存错误!' . $this->_putawayData['putaway_lot_number']);
                return false;
            }

        } else {
            //使用新货架,更新pallet
            $plan = new Plan_Service_Plan();
            $option = array('type' => 1, "putaway_code" => $this->_putawayData['putaway_code'], "putaway_lot_number" => $this->_putawayData['putaway_lot_number']);
            $palletNum = $plan->getBatchPallet($option);
            if ($palletNum > 0) {
                if (!$plan->procPlanBalance($this->_CustomerId, "pallet", $palletNum, $this->_putawayData['putaway_code'])) {
                    throw new Exception("托盘更新失败");
                    return false;
                }
            }
            $addRow = array(
                'warehouse_id' => $this->_warehouseId,
                'customer_id' => $this->_CustomerId,
                'ws_code' => $this->_putawayData['ws_code'],
                'product_id' => $this->_putawayData['product_id'],
                'wp_quantity' => $this->_putawayData['putaway_quantity'],
                'wh_create_date' => $date,
                'wh_last_update' => $date,
            );
            //添加库存产品
            if (!Warehouse_Service_Products::add($addRow)) {
                throw new Exception('创建货架库存错误!');
                return false;
            }
            $this->CreateWarehouseProductsLog('putaway,new shelf status 0 to 1,quantity:0 to ' . $this->_putawayData['putaway_quantity']);
        }
        return true;
    }

    /*
     * 货架使用日志
     */
    private function CreateWarehouseProductsLog($note = null, $type = 1)
    {
        $WarehouseProductsLog = array(
            'wpl_refId' => $this->_putawayData['putaway_code'],
            'user_id' => $this->_userId,
            'warehouse_id' => $this->_putawayData['warehouse_id'],
            'ws_code' => $this->_putawayData['ws_code'],
            'wpl_proc_type' => $type,
            'wpl_add_time' => date('Y-m-d H:i:s'),
            'wpl_note' => $note,
        );
        if (!Warehouse_Service_Products::CreateWarehouseProductsLog($WarehouseProductsLog)) {
            throw new Exception('写入货架使用日志失败!' . $this->_putawayData['putaway_lot_number']);
            return false;
        }
        return true;
    }


    /*
     * 添加批次库存/日志
     */
    private function createProductsBatch()
    {
        //add 产品上架批次表
        $date = date('Y-m-d H:i:s');
        $addWPB = array(
            'ws_code' => $this->_putawayData['ws_code'],
            'putaway_code' => $this->_putawayData['putaway_code'],
            'receiving_code' => $this->_putawayData['receiving_code'],
            'putaway_lot_number' => $this->_putawayData['putaway_lot_number'],
            'wpb_quantity' => $this->_putawayData['putaway_quantity'],
            'product_id' => $this->_putawayData['product_id'],
            'wpb_status' => 1,
            'qco_code' => $this->_putawayData['qco_code'],
            'wpb_create_time' => $date,
            'wpb_last_update' => $date
        );
        $this->_putawayData['wpb_id'] = Warehouse_Service_ProductsBatch::create($addWPB);
        if ($this->_putawayData['wpb_id'] < 1) {
            throw new Exception('创建库存批次失败.' . $this->_putawayData['putaway_lot_number']);
            return false;
        }
        $this->createProductUseageLog('putaway');
        return true;
    }

    /*
     * 批次日志
     */
    private function createProductUseageLog($note = null, $procType = 1)
    {
        $add = array(
            'wpu_type' => 1,
            'wpu_proc_type' => $procType,
            'wpu_refId' => $this->_putawayData['putaway_code'],
            'wpu_current_qty' => $this->_putawayData['putaway_quantity'],
            'wpu_quantity' => $this->_putawayData['putaway_quantity'],
            'wpu_note' => $note,
            'wpb_id' => $this->_putawayData['wpb_id'],
            'wpu_create_time' => date("Y-m-d H:i:s"),
        );
        if (!Warehouse_Service_ProductUseage::create($add)) {
            throw new Exception('写入批次日志失败.');
            return false;
        }
        return true;
    }
    /*
     * 上架日志
     */
    private  function createPutawayLog($type=0,$status=0,$putawayCode,$note=''){
        $rows=array(
            'putaway_code'=> $putawayCode,
            'pl_type'=> $type,
            'customer_id'=> $this->_CustomerId,
            'pl_statu_now'=>$status,
            'pl_note'=>$note
        );
        if(!Product_Service_Putaway::createPutawayLog($rows)){
            throw new Exception('写入上架日志失败.');
            return false;
        }
         return true;
    }

    /*
     * 更新ASN、QC 上架数量
     * param $productid=>产品ID , $qty=>上架数量
     */
    private  function  updateAsnOrQcPutawayQty($productId=0,$qty=0){
        $date=date('Y-m-d H:i:s');
        $where = array(
            'product_id' => $productId,
            'receiving_code' => $this->_receivingCode,
        );
        $asnItemRows = Product_Service_ReceivingItem::getByReceivingAsnPid($where);
        $updateRow = array(
            'putaway_qty' => $asnItemRows['putaway_qty'] + $qty ,
        );
        //避免上架数量大于QC通过的数量
        if($updateRow['putaway_qty'] > $asnItemRows['received_qty']){
            throw new Exception('更新ASN上架数量失败,上架数量不能大于QC通过数量.'.$productId);
            return false;
        }
        if (!Product_Service_ReceivingItem::updateAsnPid($updateRow, $where)) {
            throw new Exception('更新ASN上架数量失败.'.$productId);
            return false;
        }
        //更新QC上架数量,避免与AanItem数量不符，用AsnItem上架数量
        $qcModel=new Product_Model_QualityControlOrder();
        $qcItemModel= new Product_Model_QualityControlItem();
            $qcWhere=array(
                'qco_ref_code'=>$this->_receivingCode,
                'product_id'=>$productId
            );
            $qcRow=$qcModel->getJoinQcItem($qcWhere);

            if(!$qcItemModel->updateByQcoCodeAndProductId(array('qci_putaway_qty'=>$updateRow['putaway_qty'],'qci_last_update'=>$date),$qcRow['qco_code'],$productId)){
                throw new Exception('更新QC上架数量失败.'.$qcRow['qco_code']);
                return false;
            }
        return true;
    }


}